package com.sign.common.util.threadpool;

import java.util.concurrent.*;

/**
 * @Author 513422479@qq.com
 * Date on 2020/5/21  21:34
 */
public class ThreadPoolUtils {
    private ExecutorService executorService;

    ThreadPoolUtils(int threadNum, String poolName){
        executorService=getNewFixedThreadPool(threadNum,poolName);
    }

    public ExecutorService getExecutor(){
        return executorService;
    }

    private ExecutorService getNewFixedThreadPool(int threadNum, String poolName){
     return  new ThreadPoolExecutor(threadNum,threadNum,0L,
             TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(),
             new NamedThreadFactory(poolName)){
         @Override
         protected  void afterExecute(Runnable r,Throwable t){
             super.afterExecute(r,t);
             if(t==null && r instanceof Future<?>){
                 try {
                     ((Future<?>)r).get();
                 } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
                     e.printStackTrace();
                 } catch (ExecutionException e) {
                     e.printStackTrace();
                 }
             }
             if(null != t){
                 System.out.println("thread running failed"  + t);
             }
         }
     };
    }

    /**
     * 提交 Runnable
     * @param r Runnable
     * @return
     */
    public Future<?> submitRunnable(Runnable r){
       if(r == null){
           return  null;
       }
       return  getExecutor().submit(r);
    }

    /**
     * 提交callable
     * @param c
     * @return
     */
    public Future<?> submitCallabe(Callable<?> c){
        if(c == null){
            return  null;
        }
        return  getExecutor().submit(c);
    }
}
